﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain.BOM;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;
using T.E.ERP.Write.API.Applicantions.Command.BOMCommand;
using Microsoft.EntityFrameworkCore;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using B.S.DataBase.MyProject.Infrastructure;
using Yitter.IdGenerator;
using static Microsoft.EntityFrameworkCore.Design.OperationExecutor;

namespace T.E.ERP.Write.API.Applicantions.CommandHandler.BOMCommandHandler
{
    /// <summary>
    /// BOM工单添加命令处理
    /// 物联网-智能MES生产管理系统-01-BOM管理V1.1-20250206
    /// </summary>
    public class AddBomInfoCommandHandler : IRequestHandler<AddBomInfoCommand, APIResult<int>>
    {

        /// <summary>
        /// BOM信息仓储
        /// </summary>
        private readonly IBaseRepository<BomInfo> bomRep;
        /// <summary>
        /// BOM配件仓储
        /// </summary>
        private readonly IBaseRepository<BomParts> partsRep;
        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;
        private readonly SDbContext db;
        private readonly IBaseRepository<ProcessInfo> procesRep;
        private readonly IBaseRepository<OperationRecord> operatRep;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="bomRep">BOM信息仓储</param>
        /// <param name="partsRep">BOM配件仓储</param>
        /// <param name="mapper">映射</param>
        public AddBomInfoCommandHandler(IBaseRepository<BomInfo> bomRep, IBaseRepository<BomParts> partsRep, IMapper mapper, SDbContext db, IBaseRepository<ProcessInfo> procesRep, IBaseRepository<OperationRecord> operatRep)
        {
            this.bomRep = bomRep;
            this.partsRep = partsRep;
            this.mapper = mapper;
            this.db = db;
            this.procesRep = procesRep;
            this.operatRep = operatRep;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回受影响的行数</returns>
        public async Task<APIResult<int>> Handle(AddBomInfoCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            //开启事务
            using (var transaction = await db.Database.BeginTransactionAsync(cancellationToken))
            {
                try
                {
                    string currentDate = DateTime.Now.ToString("yyyyMMddHHmmss");
                    BomInfo bominfo = new BomInfo();
                    bominfo.BomCode = YitIdHelper.NextId().ToString();
                    bominfo.DefaultBom = request.DefaultBom;
                    bominfo.ProductType = request.ProductType;
                    bominfo.ProductName = request.ProductName;
                    bominfo.Remarks = request.Remarks;
                    bominfo.ProductionNum = request.ProductionNum;
                    bominfo.BomTheme = request.BomTheme;
                    bominfo.BomVersion = request.BomVersion;
                    bominfo.EstimatedCost = "8000";
                    bominfo.Inventory = 450;
                    bominfo.CreateName = request.CreateName;
                    bominfo.CreateDate = DateTime.Now;
                    var add1 = await bomRep.Add(bominfo);
                    if (add1 > 0)
                    {
                        request.BomParts.ForEach(c =>
                        {
                            c.BomCode = bominfo.BomCode;
                            c.PartsCode = "BM" + DateTime.Now.ToString("yyyyMMdd");
                            c.Inventory = 5;
                            c.AvailableProduce = 5;
                        });
                        //添加物料
                        int add2 = await partsRep.AddRanges(request.BomParts);
                        //添加工艺流程
                        int add3 = await procesRep.AddRanges(request.ProcessInfo);

                        result.Code = APIEnum.添加成功;
                        result.Msg = APIEnum.添加成功.ToString();
                        OperationRecord operation = new OperationRecord();
                        operation.OperationName = "张龙";
                        operation.OperationDate = DateTime.Now;
                        operation.OperationInfo = "新增";
                        int add4=await operatRep.Add(operation);
                        //提交事务
                        await transaction.CommitAsync(cancellationToken);
                    }
                    else
                    {
                        result.Code = APIEnum.添加失败;
                        result.Msg = APIEnum.添加失败.ToString();
                        //回滚事务
                        await transaction.RollbackAsync(cancellationToken);
                    }
                }
                catch (Exception ex)
                {
                    // 输出详细的错误信息
                    string errorMessage = $"添加失败: {ex.Message}";
                    if (ex.InnerException != null)
                    {
                        errorMessage += $" 内部异常: {ex.InnerException.Message}";
                    }
                    result.Code = APIEnum.添加失败;
                    result.Msg = errorMessage;
                    await transaction.RollbackAsync(cancellationToken);
                }
            }
            return result;
        }
    }
}